<?php

App::uses('Component', 'Controller');

class ReportExportComponent extends Component {
    
    public $components = array('Session');

    public function exportToCSV($report_id, $filename) {
        
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Type: text/csv");
        
        $report = $this->Session->read('report');
        $report['ReportColumn'] = $this->Session->read('report_columns');
        $params = $this->Session->read('report.params');
        
        $rows = ClassRegistry::init('Report')->generate($report_id, $params);

        $row = array();
        foreach ($report['ReportColumn'] as $column) {
            $row[] = '"' . $column['ReportColumnOption']['display_name'] . '"';
        }

        echo implode(",", $row) . "\r\n";


        foreach ($rows['Results'] as $row) {
            $row_arr = array();

            foreach ($report['ReportColumn'] as $column) {
                $field_name = $column['ReportColumnOption']['field_name'];
                $value = "";
                
                if(strstr($field_name, ".") != false) {
                    $parts = explode(".", $field_name);
                
                    if (count($parts) > 1) {
                        if (isset($row[$parts[0]][$parts[1]])) {
                            $value = $row[$parts[0]][$parts[1]];
                        } else if (isset($row[0][$parts[1]])) {
                            $value = $row[0][$parts[1]];
                        } else {
                            $value = '';
                        }
                    }
                }
                else if( isset($row[0][$field_name]) ) {
                    $value = $row[0][$field_name];
                }

                $row_arr[] = is_numeric($value) ? "'$value" : "\"$value\"";
            }

            echo implode(",", $row_arr) . "\r\n";
        }
    }

}
